package com.example.security;

import com.example.util.SimpleJwtTokenUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

/**
 * JWT认证过滤器 - 增强安全版本
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final SimpleJwtTokenUtil jwtTokenUtil;
    
    // 不需要认证的路径模式
    private static final List<Pattern> EXCLUDED_PATHS = List.of(
        Pattern.compile("^/api/auth/.*"),
        Pattern.compile("^/api/public/.*"),
        Pattern.compile("^/ws.*"),
        Pattern.compile("^/actuator/health.*"),
        Pattern.compile("^/swagger-ui/.*"),
        Pattern.compile("^/v3/api-docs.*"),
        Pattern.compile("^/swagger-resources/.*"),
        Pattern.compile("^/webjars/.*"),
        Pattern.compile("^/favicon.ico"),
        Pattern.compile("^/error")
    );

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request,
                                  @NonNull HttpServletResponse response,
                                  @NonNull FilterChain filterChain) throws ServletException, IOException {
        
        try {
            // 检查是否为排除路径
            String requestPath = request.getRequestURI();
            if (isExcludedPath(requestPath)) {
                filterChain.doFilter(request, response);
                return;
            }

            // 获取JWT token
            String token = getTokenFromRequest(request);
            
            if (token != null && jwtTokenUtil.validateToken(token)) {
                String username = jwtTokenUtil.getUsernameFromToken(token);
                String userType = jwtTokenUtil.getUserTypeFromToken(token);
                
                if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    // 创建认证对象
                    UsernamePasswordAuthenticationToken authentication = createAuthentication(username, userType, request);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    
                    log.debug("用户认证成功: {} ({})", username, userType);
                    
                    // 检查token是否即将过期，如果是则在响应头中提示
                    if (jwtTokenUtil.isTokenExpiringSoon(token)) {
                        response.setHeader("X-Token-Expiring", "true");
                        response.setHeader("X-Token-Remaining", jwtTokenUtil.getTokenRemainingTime(token).toString());
                    }
                }
            } else if (token != null) {
                // Token无效，记录日志
                log.warn("无效的JWT token: {}", request.getRemoteAddr());
                response.setHeader("X-Auth-Error", "Invalid token");
            }
            
        } catch (Exception e) {
            log.error("JWT认证过滤器异常: {}", e.getMessage(), e);
            // 清除认证上下文
            SecurityContextHolder.clearContext();
        }
        
        filterChain.doFilter(request, response);
    }

    /**
     * 从请求中获取JWT token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        // 1. 从Authorization头获取
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        
        // 2. 从查询参数获取（用于WebSocket等场景）
        String tokenParam = request.getParameter("token");
        if (StringUtils.hasText(tokenParam)) {
            return tokenParam;
        }
        
        // 3. 从Cookie获取（可选）
        if (request.getCookies() != null) {
            for (var cookie : request.getCookies()) {
                if ("access_token".equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        
        return null;
    }

    /**
     * 创建认证对象
     */
    private UsernamePasswordAuthenticationToken createAuthentication(String username, String userType, HttpServletRequest request) {
        // 根据用户类型设置权限
        List<SimpleGrantedAuthority> authorities = getUserAuthorities(userType);
        
        UsernamePasswordAuthenticationToken authentication = 
            new UsernamePasswordAuthenticationToken(username, null, authorities);
        
        // 设置请求详情
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        
        return authentication;
    }

    /**
     * 根据用户类型获取权限
     */
    private List<SimpleGrantedAuthority> getUserAuthorities(String userType) {
        return switch (userType != null ? userType.toUpperCase() : "USER") {
            case "ADMIN" -> List.of(
                new SimpleGrantedAuthority("ROLE_ADMIN"),
                new SimpleGrantedAuthority("ROLE_USER"),
                new SimpleGrantedAuthority("ROLE_MERCHANT")
            );
            case "MERCHANT" -> List.of(
                new SimpleGrantedAuthority("ROLE_MERCHANT"),
                new SimpleGrantedAuthority("ROLE_USER")
            );
            default -> List.of(new SimpleGrantedAuthority("ROLE_USER"));
        };
    }

    /**
     * 检查是否为排除路径
     */
    private boolean isExcludedPath(String path) {
        return EXCLUDED_PATHS.stream().anyMatch(pattern -> pattern.matcher(path).matches());
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        // OPTIONS请求不需要过滤
        return "OPTIONS".equals(request.getMethod());
    }
}
